<template>
  <div class="data-mapping-node-form">
    <h4> {{ title }} </h4>

    <el-form ref="form" :model="form" :rules="rules" label-width="0">
      <el-row :gutter="10">
        <el-col :span="12">
          <p>输入端接口：</p>
          <el-form-item prop="provideServiceId">
            <el-select v-model="form.provideServiceId" multiple clearable placeholder="请选择服务" @change="serviceChange(1)">
              <el-option
                v-for="(item, index) in dataMapping.providerList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <p>
            映射信息：<el-button type="small" @click="addLine"> 新建 </el-button>
          </p>
        </el-col>
        <el-col :span="12">
          <p>输出端接口：</p>
          <el-form-item prop="requestServiceId">
            <el-select v-model="form.requestServiceId" placeholder="请选择服务" @change="serviceChange(2)">
              <el-option
                v-for="(item, index) in dataMapping.supplicantList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!-- <p>
            拆分发送：
            <el-switch
              v-model="form.split"
              active-text="开"
              active-value="1"
              active-color="#87D068"
              inactive-text="关"
              inactive-value="0"
              inactive-color="#D9001B"
            />
          </p> -->
        </el-col>
      </el-row>
      <!-- 映射字段列表 -->
      <div class="mapping-field-container">
        <el-row :gutter="10" class="mapping-field-title">
          <el-col :span="8"> 输入端 </el-col>
          <el-col :span="4" style="border:1px solid transparent" />
          <el-col :span="8"> 输出端 </el-col>
        </el-row>
        <el-row v-for="(item, index) in mappingFieldList" :key="index" :gutter="10" class="mapping-field-list">
          <el-col :span="8"> <el-button type="text" @click="chooseField(item, index, 1)"> {{ item.sourceFieldName.length > 13 ? item.sourceFieldName.slice(0, 13) + '...' : item.sourceFieldName }} </el-button> </el-col>
          <el-col :span="4" class="arrow"> <i class="el-icon-back" /> <i class="el-icon-right" /> </el-col>
          <el-col :span="8"> <el-button type="text" @click="chooseField(item, index, 2)"> {{ item.targetFieldName.length > 13 ? item.targetFieldName.slice(0, 13) + '...' : item.targetFieldName }} </el-button> </el-col>
          <el-col :span="4">
            <el-button size="small" type="text" class="text-del-btn" @click="delLine(index)"> 删除行 </el-button>
          </el-col>
        </el-row>
      </div>

      <el-form-item label-width="0">
        <el-button size="small" @click="cancelForm">取消</el-button>
        <el-button size="small" type="primary" @click="submitForm('form')">确定</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      custom-class="mapping-field-dialog"
      title="接口字段选择"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      width="800px"
    >
      <el-select
        v-if="fieldCurrentType === 1"
        v-model="supplicantInDialog"
        placeholder="请选择服务"
        @change="supplicantInDialogChange"
      >
        <el-option
          v-for="(item, index) in supplicantListInDialog"
          :key="index"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <p>
        <el-checkbox v-model="selectAll" @change="selectAllChange"> 选择全部 </el-checkbox>
      </p>
      <el-table
        ref="singleTable"
        border
        :data="tableData"
        highlight-current-row
        lazy
        :load="load"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @current-change="handleCurrentChange"
      >
        <el-table-column
          label="字段标识"
          prop="field"
        />
        <el-table-column
          label="字段备注"
          prop="fieldName"
        />
        <el-table-column
          label="字段类型"
          prop="field_type"
        >
          <template slot-scope="{ row }">
            {{ getDictText('field_type', row.fieldType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="小数位"
          prop="fieldDecimal"
        />
        <el-table-column
          label="字段长度"
          prop="fieldLength"
        />
        <el-table-column
          label="备注"
          prop="remarks"
        />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="fieldConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fieldTreeListApi } from '@/api/serviceManage/requestPartyServiceManage'
import dictMixin from '@/utils/mixins/dict'
export default {
  mixins: [
    dictMixin(['field_type'])
  ],
  props: {
    requestSystemId: {
      type: String,
      default: ''
    },

    title: {
      type: String,
      default: ''
    },

    dataMapping: {
      type: Object,
      default: () => {}
    }
  },

  data () {
    return {
      dialogVisible: false,
      mappingFieldList: [],
      form: {
        provideServiceId: [],
        requestServiceId: '',
        split: '0',
        field: []
      },
      rules: {
        provideServiceId: { required: true, message: '请选择输入端接口', trigger: 'change' },
        requestServiceId: { required: true, message: '请选择输出端接口', trigger: 'change' }
      },
      tableData: [],
      // 输入端备份的数据
      leftList: [],
      // 输出端备份的数据
      rightList: [],
      // 选择全部
      selectAll: false,
      currentRow: null,
      fieldCurrentIndex: null,
      fieldCurrentType: null,
      // 接口字段选择中的 输入端接口服务
      supplicantListInDialog: [],
      supplicantInDialog: ''
    }
  },

  created () {
  },

  methods: {
    // 初始化form
    async initForm (data) {
      let provideServiceId = []
      if (data.provideServiceIds) {
        provideServiceId = data.provideServiceIds.split(',')
      }
      this.form = {
        provideServiceId: data ? provideServiceId : [],
        requestServiceId: data ? data.requestServiceId : '',
        split: data ? data.split : '0',
        field: []
      }
      this.mappingFieldList = (data && data.field) ? data.field : []
      await this.$nextTick()
      this.$refs.form.clearValidate()
    },

    // 服务切换
    serviceChange (val) {
      if (val === 1) {
        this.leftList = []
      } else if (val === 2) {
        this.rightList = []
      }
    },

    // 字段确定弹框
    fieldConfirm () {
      if (!this.currentRow && !this.selectAll) {
        return this.$message.warning('请选择字段')
      }
      this.dialogVisible = false
      let name = ''
      if (this.fieldCurrentType === 1) {
        if (this.selectAll) {
          name = this.dataMapping.providerList.filter(item => item.id === this.supplicantInDialog)[0].name
        }
        this.mappingFieldList[this.fieldCurrentIndex].sourceFieldName = this.selectAll ? name : this.currentRow.fieldName
        this.mappingFieldList[this.fieldCurrentIndex].sourceFieldId = this.selectAll ? -1 : this.currentRow.id
        this.mappingFieldList[this.fieldCurrentIndex].sourceManagerId = this.supplicantInDialog
      } else {
        if (this.selectAll) {
          name = this.dataMapping.supplicantList.filter(item => item.id === this.form.requestServiceId)[0].name
        }
        this.mappingFieldList[this.fieldCurrentIndex].targetFieldName = this.selectAll ? name : this.currentRow.fieldName
        this.mappingFieldList[this.fieldCurrentIndex].targetFieldId = this.selectAll ? -1 : this.currentRow.id
        this.mappingFieldList[this.fieldCurrentIndex].targetManagerId = this.form.requestServiceId
      }
    },

    // 单选字段
    handleCurrentChange (val) {
      if (val) {
        this.currentRow = val
        this.selectAll = false
      }
    },

    // 选择全部
    selectAllChange (val) {
      if (this.selectAll) this.$refs.singleTable.setCurrentRow(null)
    },

    // 字段弹框
    chooseField (item, index, type) {
      this.fieldCurrentIndex = index
      this.fieldCurrentType = type
      this.dialogVisible = true
      this.currentRow = null
      this.tableData = []
      this.selectAll = false
      this.supplicantInDialog = item.sourceManagerId
      if ((type === 1 && item.sourceFieldId === -1) || (type === 2 && item.targetFieldId === -1)) {
        this.selectAll = true
      }
      this.$nextTick(() => {
        this.$refs.singleTable.setCurrentRow(null)
      })
      if (type === 1 && this.leftList.length !== 0) {
        // this.tableData = this.leftList
        // return
      } else if (type === 2 && this.rightList.length !== 0) {
        this.tableData = this.rightList
        return
      }

      if (type === 2) {
        fieldTreeListApi({
          serviceManagerId: this.form.requestServiceId,
          parentId: -1
        })
          .then(({ code, data }) => {
            if (code === '00000') {
              this.tableData = data.map(item => {
                return {
                  ...item,
                  hasChildren: true
                }
              })
              this.rightList = this.tableData
            }
          })
      } else {
        this.supplicantListInDialog = []
        this.dataMapping.providerList.forEach(item => {
          if (this.form.provideServiceId.indexOf(item.id) !== -1) {
            this.supplicantListInDialog.push(item)
          }
        })
        fieldTreeListApi({
          serviceManagerId: this.supplicantInDialog,
          parentId: -1
        })
          .then(({ code, data }) => {
            if (code === '00000') {
              this.tableData = data.map(item => {
                return {
                  ...item,
                  hasChildren: true
                }
              })
              this.leftList = this.tableData
            }
          })
      }
    },

    // 接口字段选择弹框中的下拉选择
    supplicantInDialogChange () {
      fieldTreeListApi({
        serviceManagerId: this.supplicantInDialog,
        parentId: -1
      })
        .then(({ code, data }) => {
          if (code === '00000') {
            this.tableData = data.map(item => {
              return {
                ...item,
                hasChildren: true
              }
            })
            this.leftList = this.tableData
          }
        })
        .catch(() => {})
    },

    // 懒加载表格
    load (tree, treeNode, resolve) {
      fieldTreeListApi({
        serviceManagerId: this.fieldCurrentType === 1 ? this.form.provideServiceId : this.form.requestServiceId,
        parentId: tree.id
      })
        .then(({ code, data }) => {
          if (code === '00000') {
            resolve(data.map(item => {
              return {
                ...item,
                hasChildren: true
              }
            }))
          }
        })
    },

    // 添加行按钮
    addLine () {
      if (this.form.provideServiceId.length === 0 || !this.form.requestServiceId) {
        return this.$message.warning('请选择输入端接口和输出端接口')
      }
      this.mappingFieldList.push({
        sourceFieldId: '',
        sourceFieldName: '选择字段',
        targetFieldId: '',
        targetFieldName: '选择字段'
      })
    },

    // 删除行按钮
    delLine (index) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.mappingFieldList.splice(index, 1)
      })
    },

    // 确定
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.mappingFieldList.length === 0) {
            return this.$message.warning('至少有一条映射信息')
          }
          if (!this.mappingFieldList.every(item => !!item.sourceFieldId && !!item.targetFieldId)) {
            return this.$message.warning('请将映射信息补充完整')
          }
          this.form.field = this.mappingFieldList
          const form = Object.assign({}, this.form)
          form.provideServiceIds = this.form.provideServiceId.join(',')
          form.provideServiceId = this.form.provideServiceId[0]
          this.$emit('nodeForm', form)
        }
      })
    },
    // 取消
    cancelForm () {
      this.$emit('nodeForm')
    }
  }
}
</script>

<style lang="scss" scoped>
.data-mapping-node-form {
  .mapping-field-container {
    margin: 10px 0 20px;
    .el-row {
      .el-col {
        text-align: center;
      }
    }

    .mapping-field-title {
      font-size: 18px;
      color: #1296DB;
    }

    .mapping-field-list {
      margin-top: 10px;
    }

    .arrow {
      line-height: 36px;
      font-size: 18px;
    }
  }
}
::v-deep .mapping-field-dialog {
  .el-table {
    margin-top: 10px;
  }
  .el-table__row {
    cursor: pointer;
  }
}
</style>
